package com.easonji.admin.controller;

import java.util.List;

import javax.annotation.Resource;

import com.easonji.admin.manager.PermissionManager;
import com.easonji.admin.manager.UserManager;
import com.easonji.core.log.factory.LogTaskFactory;
import com.easonji.core.shiro.ShiroUser;
import com.easonji.core.shiro.util.ShiroUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.easonji.admin.service.UserService;
import com.easonji.common.base.controller.BaseController;
import com.easonji.common.constant.Consts;
import com.easonji.common.node.MenuNode;
import com.easonji.common.util.HttpUtils;
import com.easonji.common.util.StringUtils;
import com.easonji.config.properties.SysProperties;
import com.easonji.core.log.LogManager;
import com.google.code.kaptcha.Constants;

/**
 * @ClassName: LoginController
 * @Description: 登录控制器
 * @Author: LiuJun
 * @date: 2018/07/08 17:42
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Controller
public class LoginController extends BaseController {

    @Resource
    private SysProperties sysProperties;

    @Resource
    private PermissionManager permissionManager;

    @Resource
    private UserService userService;

    @Resource
    private UserManager userManager;

    /**
     * 跳转到主页
     */
    @GetMapping("")
    public String index(Model model) {
        // 获取菜单列表
        List<Integer> roleIds = ShiroUtils.getUser().getRoleIds();
        if (roleIds == null || roleIds.size() == 0) {
            ShiroUtils.getSubject().logout();
            model.addAttribute("tip", "该用户没有角色，无法登陆");
            return "/login";
        }
        List<MenuNode> menus = permissionManager.queryMenuNode(Consts.DEFAULT_APP_ID, roleIds);
        model.addAttribute("menus", menus);
        ShiroUser shiroUser = ShiroUtils.getUser();
        model.addAttribute("userName", shiroUser.getName());
        model.addAttribute("deptName", shiroUser.getDeptName());
        model.addAttribute("sex", shiroUser.getSex());
        return "/index";
    }

    /**
     * 跳转到登录页面
     */
    @GetMapping("/login")
    public String login(Model model) {
        model.addAttribute("kaptchaOpen", sysProperties.getKaptchaOpen());
        if (ShiroUtils.isAuthenticated() || ShiroUtils.getUser() != null) {
            return REDIRECT + "/";
        } else {
            return "/login";
        }
    }

    /**
     * 点击登录执行的动作
     */
    @PostMapping("/login")
    public String loginVali(Model model, @ModelAttribute(value = "userName") String userName,
            @ModelAttribute(value = "passWord") String passWord, @ModelAttribute(value = "remember") String remember) {
        // 验证验证码是否正确
        if (sysProperties.getKaptchaOpen()) {
            String kaptcha = super.getParameter("kaptcha").trim();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (StringUtils.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                model.addAttribute("tip", "验证码错误，无法登陆");
                model.addAttribute("kaptchaOpen", sysProperties.getKaptchaOpen());
                return "/login";
            }
        }
        Subject currentUser = ShiroUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord.toCharArray());
        String defRemember = "on";
        if (defRemember.equals(remember)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }
        currentUser.login(token);
        ShiroUser shiroUser = ShiroUtils.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getUserId(), HttpUtils.getIp()));
        ShiroUtils.getSession().setAttribute("sessionFlag", true);
        return REDIRECT + "/";
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logOut() {
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroUtils.getUser().getUserId(), HttpUtils.getIp()));
        ShiroUtils.getSubject().logout();
        return REDIRECT + "/login";
    }
}
